1 using System.Collections;
2 using
System.Collections.Generic;
3 using
UnityEngine;
4 using
System;
5
6 public
class Movable : Scalable {
7
8     
[SerializeField]
9     
protected float speed = 2f;
10     
protected Coroutine moveCoroutine;
11
12     
protected override void Start() {
13         
base.Start();
14     }
15
16     
public virtual void MoveToXZ(Node node, Action finishCallback) {
17         StopMoveCoroutine();
18         moveCoroutine = StartCoroutine(IEMoveToXZ(node, finishCallback));
19     }
20
21     
public virtual void MoveBy(Vector3 addPos, Action finishCallback) {
22         StopMoveCoroutine();
23         moveCoroutine = StartCoroutine(IEMoveBy(addPos, finishCallback));
24     }
25
26     
protected virtual void StopMoveCoroutine() {
27         
if (moveCoroutine != null) {
28             StopCoroutine(moveCoroutine);
29         }
30     }
31
32     
protected virtual IEnumerator IEMoveBy(Vector3 addPos, Action finishCallback) {
33         ready =
false;
34         Vector3 origPos = transform.position;
35         Vector3 targPos = origPos + addPos;
36         
37         
while (true) {
38             
if (IsNear(targPos)) {
39                 ready =
true;
40                 
if (finishCallback != null) finishCallback();
41                 
yield break;
42             }
43             transform.position = Vector3.MoveTowards(transform.position,targPos,speed * Time.deltaTime);
44
45             
yield return null;
46         }
47     }
48
49     
protected virtual IEnumerator IEMoveToXZ(Node node, Action finishCallback) {
50         ready =
false;
51         Vector3 origPos = transform.position;
52         Vector3 targPos = node.transform.position;
53         targPos.y = origPos.y;
54         
while (true) {
55             
if (IsNear(targPos)) {
56                 ready =
true;
57                 
if (finishCallback != null) finishCallback();
58                 
yield break;
59             }
60             transform.position = Vector3.MoveTowards(transform.position,targPos,speed * Time.deltaTime);
61             
yield return null;
62         }
63     }
64
65     
protected virtual bool IsNear(Vector3 targPos) {
66         
return (transform.position - targPos).sqrMagnitude < .01f;
67     }
68 }


Gõ tìm kiếm nhanh...